<?php
namespace app\minprogram\controller;
use app\minprogram\model\Battery;
use app\minprogram\model\BatteryOrder;
use app\api\model\User;
use app\common\utils\BackNotify;
use think\Controller;
use app\common\utils\Redis;
use think\Request;
use think\Db;
// 购买商品流程
class Order extends Common
{

    // 添加购物车
    public function getAddCar(Request $request){

        $user_id=$this->checkLoginUser(true);

        $goods_id=$request->param('goods_id');

        $redis =Redis::instance();

        // $redis->hset('用户id','商品id','商品数量');

        $redis->hIncrBy(BatteryOrder::getCarKey($user_id),$goods_id,1);
//        $goods_num=$redis->hget($key,$goods_id);
//
//        if($goods_num){
//            $goods_num++;
//            $redis->hset($user_id,$goods_id,$goods_num);
//        }else{
//            $redis->hset($user_id, $goods_id, 1);
//        }

        to_json_encode(200, 'success', ['status'=>true]);
    }

    // 修改购物车商品数量
    public function getChangeCarSum(Request $request){

        $user_id = $this->checkLoginUser(true);
        $goods_id = $request->param('goods_id');
        $sum=$request->param('sum');

        $redis = Redis::instance();

        if($sum == 0){
            $redis->hdel(BatteryOrder::getCarKey($user_id),$goods_id);
        }else{
            $redis->hset(BatteryOrder::getCarKey($user_id),$goods_id,$sum);
        }

        to_json_encode(200, 'success', true);
    }

    // 显示购物车商品列表
    public function getShowCarList(){

        $user_id = $this->checkLoginUser(true);

        $redis = Redis::instance();

        $list=$redis->hgetall(BatteryOrder::getCarKey($user_id));

       // $goodsModel = new \app\admin\model\GoodsModel();

        $carList=[];
        $i=0;
        foreach ($list as $gid => $sum) {

           // $goodsInfo=$goodsModel->getGoodsInfoById($gid, 'goods_name,goods_type,price,goods_img,describe');

            $goodsInfo=Battery::handleGoodsInfo(Battery::getGoodsInfo($gid,true),true);
            $carList[$i]['goods_id']=$gid;
            $carList[$i]['goods_name']= $goodsInfo['goods_name'];
            $carList[$i]['goods_type']= $goodsInfo['goods_type'];
            $carList[$i]['price']= $goodsInfo['price'];
            $carList[$i]['goods_img']= $goodsInfo['goods_img'];
            $carList[$i]['describe']= $goodsInfo['describe'];
            $carList[$i]['sum']=$sum;
            $i++;
        }

        to_json_encode(200,'success',$carList);
    }

    // 提交订单
    
      public function postGenerateOrder(Request $request){
     /* 参数
    user_id
    array(
        id1 => sum1,
        id2 => sum2,
    )
    address_id
    */
            $user_id = $this->checkLoginUser(true);

         // $user_id =74;
         //   $redis =Redis::instance();

            // 生成订单
          $param=$request->post();

//          $param=<<<E
//          {"orderInfo":[{"goods_id":1,"num":3},{"goods_id":2,"num":4},{"goods_id":7,"num":4}],"addressId":2,"payType":4}
//E;
//
//          $param=json_decode($param,true);

          $order_info = $param['orderInfo'];


          $address_id=$param['addressId'];

          //当 使用 默认 地址时，判断 是否 填写了 默认地址
          if($address_id == 0)
          {
              to_json_encode(400, '请补全地址信息',array('status'=>false) );
//              $user_info = User::getExtendInfo($user_id);
//              if(empty($user_info['address']))
//              {
//                  to_json_encode(400, '请补全地址信息',array('status'=>false) );
//
//              }
          }
          //默认选择货到付款
            if(!isset($param['payType']))
            {
                $payType =1;
            }else{
                $payType =$param['payType'];
            }

           $delivery_time=0;
           if(isset($param['deliveryTime']))
           {
               $delivery_time=$param['deliveryTime'];
           }
           if(!$delivery_time)
           {
               $delivery_time=date('Y-m-d');
           }

            $res =BatteryOrder::generateGoodsOrders($user_id,$order_info,$address_id,$payType,$delivery_time);

            if($res['status']){
                // 生成订单成功
//                foreach ($order_info as $gid => $num) {
//                   // $redis->hdel($user_id,$gid);
//                }

                BackNotify::addNotifyNum(BatteryOrder::getNotifyParam($res['order_id']));
                to_json_encode(200, 'success',array('order_id'=>$res['order_id']));
            }else{
                to_json_encode(400, $res['msg'],array('status'=>false) );
            }
        }

    // 预约订单列表
   
    public function getOrderList(Request $request){
        $user_id = $this->checkLoginUser(true);


        $type = $request->param('type',0);
        $page = $request->param('page',1);

       // var_dump(BatteryOrder::getUserOrderList($user_id,0,1));
        to_json_encode(200,'success',
            BatteryOrder::handleOrderList(
                BatteryOrder::getUserOrderList($user_id,$type,$page)
                ,$user_id)
        );
    }


   public function getOrderInfo(Request $request)
   {
       $user_id = $this->checkLoginUser(true);

       $order_id = $request->param('order_id');

       if(!is_numeric($order_id))
       {
           to_json_encode(400, '参数错误',array('status'=>false) );

       }
       $order_info = BatteryOrder::getOrderInfo($order_id);
       if(empty($order_info))
       {
           to_json_encode(400, '没有订单信息',array('status'=>false) );

       }
       $order_detail = BatteryOrder::getOrderDetail($order_id,$user_id);

       if(empty($order_detail))
       {
           to_json_encode(200, 'success',array() );

       }
       $goods_list =[];
       foreach ($order_detail as $key=>$val)
       {
           $goods_list[$key]=Battery::handleGoodsInfo(Battery::getGoodsInfo($val['goods_id'],Battery::CACHE_EXPIRE_LEVEL),$user_id);
           $goods_list[$key]['num']=$val['num'];
       }

       $address_info=Db::name('address')->field('address_id,receiver_name,receiver_phone,address,house_number')->where(['address_id'=>$order_info['address_id']])->find();

       $receiver_address='';
       $receiver_name='';
       $receiver_phone='';
       if(!empty($address_info))
       {
           $receiver_address=$address_info['address'].$address_info['house_number'];
           $receiver_name=$address_info['receiver_name'];
           $receiver_phone=$address_info['receiver_phone'];
       }
       to_json_encode(200,'success',[
           'order_id'=>$order_id,
           'address'=>$receiver_address,
           'receiver_name'=>$receiver_name,
           'receiver_phone'=>$receiver_phone,
           'total_amount'=>$order_info['actual_amount'],
           'pay_type'=>$order_info['pay_type'],
           'add_time'=>date('Y-m-d H:i:s',$order_detail[0]['add_time']),
           'order_sn'=>$order_detail[0]['order_sn'],
           'order_status'=>$order_detail[0]['status'],
           'delivery_time'=>empty($order_info['post_delivery_time'])?'':$order_info['post_delivery_time'],
           'goods_list'=>$goods_list,
           
       ]);
   }


    // 取消订单
    public function getCancelOrder(Request $request){

        $user_id = $this->checkLoginUser(true);

        $order_id=$request->param('order_id');


        $status= BatteryOrder::getOrderStatusById($order_id);


        if(empty($status))
        {
            to_json_encode(400, '没有该订单信息', array('status'=>false));

        }
        if($status['apply_cancel'] ==1)
        {
            to_json_encode(400, '该订单已申请取消，请等待处理', array('status'=>false));

        }

        BatteryOrder::changeOrderStatusById($order_id);

        BackNotify::addNotifyNum(BatteryOrder::getNotifyParam($order_id,2));

        to_json_encode(200, 'success',array('status'=>true));


    }

   


    // 收货地址列表
    public function getAddressList(){
        $user_id = $this->checkLoginUser();

        $list=Db('address')->field('address_id,receiver_name,receiver_phone,address,house_number')->where(['user_id'=>$user_id,'is_del'=>0])->select();

	to_json_encode(200,'success',$list);

    }


    // 添加收货地址
    public function postAddressAdd(){
        $user_id = $this->checkLoginUser();

        $param=input('post.');
        $param['user_id']=$user_id;

        if($address_id = Db('address')->insertGetId($param)){
            
            to_json_encode(200, '添加地址成功', array('address_id'=>$address_id) );
        }else{
            to_json_encode(400, '添加失败',array('status'=>false));
        }
    }
    // 删除收货地址
    public function postAddressDel()
    {
        $user_id = $this->checkLoginUser();

        $address_id = input('address_id');

        if (Db('address')->where('address_id',$address_id)->delete()) {

            to_json_encode(200, '删除成功', array('status'=>true));
        } else {
            to_json_encode(400, '操作失败', array('status'=>false));
        }
    }
    
    
}
